# Copyright 2009 Larry Resnik, Lasfraka-Elixir

#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.

#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.

#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.


from __future__ import division

from sys import exit
import pyglet
from pyglet.window import key
from pyglet.gl import glLoadIdentity, glScalef

class MainMenuScene(object):
    def __init__(self, manager):
        self.manager = manager
        self.background = pyglet.graphics.OrderedGroup(0)
        self.foreground = pyglet.graphics.OrderedGroup(1)
        self.batch = pyglet.graphics.Batch()

        self.scale = self.manager.settings.properties['scale'] / 100
        self.menus = {
            'top':['New Game', 'Load Game', 'Options', 'Quit'],
            'character':['Marisa', 'Arwing', 'Return'],
            'options':['BGM Volume', 'SFX Volume', 'FPS', 'Return']
        }
        # This is the currently selected label. It's an array index.
        self.selection = 0
        # This is the key for the currently in-use self.menus dict.
        self.atMenu = 'top'
        self.color = (0, 0, 0, 255)
        self.fonts = ['DejaVuSansMono']
        self.labels = []
        self.specialLabels = []
        self._change_menu(self.atMenu)

        backscene = pyglet.resource.image('titlelogo.png')
        self.backscene = pyglet.sprite.Sprite(backscene, batch=self.batch,
            group=self.background)
        self.backscene.scale = max(320 / self.backscene.width,
                                   240 / self.backscene.height)

        cursor = pyglet.resource.image('cursor-small.png')
        self.cursor = pyglet.sprite.Sprite(cursor,
            batch=self.batch, group=self.foreground)
        self.cursor.x = self.labels[0].x - self.cursor.width - 10
        self.cursor.y = self.labels[0].y

    def _change_menu(self, menuName):
        if menuName not in self.menus:
            print('%s is not a valid menu.' % menuName)
            return
        self._make_labels(self.menus[menuName], 320 / 4, 240 / 15)
        if menuName == 'options':
            self._make_option_labels(320 / 4 * 3, 240 / 15)
        self.atMenu = menuName

    def _delete_labels(self):
        for label in self.labels[:]:
            label.delete()
        self.labels = []
        for label in self.specialLabels[:]:
            label.delete()
        self.specialLabels = []

    def _make_labels(self, list, x, y):
        self._delete_labels()
        for index, item in enumerate(list):
            self.labels.append(pyglet.text.Label(item, font_size=10, x=x,
                y=y * (len(list) - index), color=self.color, batch=self.batch,
                font_name=self.fonts))#, group=self.foreground))

    def _make_option_labels(self, x, y):
        self.specialLabels.append(pyglet.text.Label(
            '%i' % int(self.manager.settings.properties['bgm_volume']),
            font_size=10, x=x, y=y * 4, color=self.color, batch=self.batch,
            font_name=self.fonts))#, group=self.foreground))
        self.specialLabels.append(pyglet.text.Label(
            '%i' % int(self.manager.settings.properties['sfx_volume']),
            font_size=10, x=x, y=y * 3, color=self.color, batch=self.batch,
            font_name=self.fonts))#, group=self.foreground))
        self._set_fps = self.manager.settings.properties['fps']
        self.specialLabels.append(pyglet.text.Label(repr(self._set_fps),
            font_size=10, x=x, y=y * 2, color=self.color, batch=self.batch,
            font_name=self.fonts))#, group=self.foreground))

    def goto_game(self, dt=0.0):
        self.manager.bgm_player.stop_sound()
        self.cleanup()
        # Stop the BGM, fade-out, then create the game scene, then start the
        # BGM, then fade-in to the game.
        self.manager.fading_scene_transition(0.0, 'game')

    def cleanup(self):
        """This removes all of this scenes resources from its batches."""
#        print('MainMenuScene cleanup.')
        self._delete_labels()
        self.backscene.delete()
        self.cursor.delete()

    def on_draw(self):
        glLoadIdentity()
        glScalef(self.manager.settings.properties['scale'] / 100.0,
                 self.manager.settings.properties['scale'] / 100.0, 1.0)
        self.batch.draw()

    def iterate_scene(self, keys):
        """Does one update cycle for this Scene."""
        if keys.up.held == 1 or (keys.up.held > 30 and keys.up.held % 5 == 0):
            self.selection -= 1
            if self.selection < 0:
                self.selection = len(self.labels) - 1
        elif keys.down.held == 1 or (keys.down.held > 30 and \
            keys.down.held % 5 == 0):
            self.selection += 1
            if self.selection > len(self.labels) - 1:
                self.selection = 0
        elif keys.select.held == 1:
            if self.atMenu == 'top':
                choice = self.menus[self.atMenu][self.selection]
                if choice == 'Quit':
                    self.cleanup()
                    exit()
                elif choice == 'Options':
                    self._change_menu('options')
                    self.selection = 0
                elif choice == 'New Game':
                    self._change_menu('character')
                elif choice == 'Load Game':
                    print('Placeholder: Load Game')
            elif self.atMenu == 'options':
                choice = self.menus[self.atMenu][self.selection]
                if choice == 'Return':
                    self.manager.enable_fps(self._set_fps)
                    self.manager.settings.write()
                    self._change_menu('top')
                    # Set at 'Options'.
                    self.selection = 2
            elif self.atMenu == 'character':
                choice = self.menus[self.atMenu][self.selection]
                if choice == 'Return':
                    self._change_menu('top')
                    # Set at 'New Game'.
                    self.selection = 0
                else:
                    if choice == 'Marisa':
                        self.manager.settings.character = 'marisa'
                    elif choice == 'Arwing':
                        self.manager.settings.character = 'arwing'
                    self.goto_game()
                    # Don't try to call move_cursor().
                    return
        elif keys.cancel.held == 1:
            if self.atMenu == 'top':
                self.selection = 3 # Set at 'Quit'.
            elif self.atMenu == 'options':
                self._change_menu('top')
                self.selection = 2 # Set at 'Options'.
            elif self.atMenu == 'character':
                self._change_menu('top')
                self.selection = 0 # Set at 'New Game'.
        elif keys.right.held == 1:
            if self.atMenu != 'options':
                # This key isn't used at this time.
                return
            choice = self.menus[self.atMenu][self.selection]
            if choice == 'BGM Volume':
                self.manager.settings.properties['bgm_volume'] += 10
                if self.manager.settings.properties['bgm_volume'] > 100:
                    self.manager.settings.properties['bgm_volume'] = 100
                self.specialLabels[0].text = '%i' % \
                    int(self.manager.settings.properties['bgm_volume'])
                self.manager.reset_bgm_volume()
            elif choice == 'SFX Volume':
                self.manager.settings.properties['sfx_volume'] += 10
                if self.manager.settings.properties['sfx_volume'] > 100:
                    self.manager.settings.properties['sfx_volume'] = 100
                self.specialLabels[1].text = '%i' % \
                    int(self.manager.settings.properties['sfx_volume'])
                self.manager.reset_bgm_volume()
            elif choice == 'FPS':
                self._set_fps = not self._set_fps
                self.specialLabels[2].text = repr(self._set_fps)
        elif keys.left.held == 1:
            if self.atMenu != 'options':
                return
            choice = self.menus[self.atMenu][self.selection]
            if choice == 'BGM Volume':
                self.manager.settings.properties['bgm_volume'] -= 10
                if self.manager.settings.properties['bgm_volume'] < 0:
                    self.manager.settings.properties['bgm_volume'] = 0
                self.specialLabels[0].text = '%i' % \
                    int(self.manager.settings.properties['bgm_volume'])
                self.manager.reset_bgm_volume()
            elif choice == 'SFX Volume':
                self.manager.settings.properties['sfx_volume'] -= 10
                if self.manager.settings.properties['sfx_volume'] < 0:
                    self.manager.settings.properties['sfx_volume'] = 0
                self.specialLabels[1].text = '%i' % \
                    int(self.manager.settings.properties['sfx_volume'])
                self.manager.reset_bgm_volume()
            elif choice == 'FPS':
                self._set_fps = not self._set_fps
                self.specialLabels[2].text = repr(self._set_fps)
        self.cursor.y = self.labels[self.selection].y
